<template>
  <div :class="prefixCls">
    <div
      class="left box-r-shadow"
      :class="{
        hide: isPreview,
      }"
    >
      <FormTitle text="应用配置" class="mb-2" />
      <div class="ml-2.5">
        <BasicForm @register="registerAppForm" @field-value-change="changeComplexContainer" />
      </div>
      <div class="mt-4" v-if="showTab">
        <FormTitle text="按钮配置" class="mb-2" />
        <!-- buttons -->
        <div class="ml-2.5">
          <HEditTable
            v-model:data="formState.buttons"
            v-if="buttonColumn.length"
            :columns="buttonColumn"
          >
            <template #title>
              <div class="actions flex mt-4 mb-2">
                <a-button type="primary" size="small" @click="handleAddBtn">新增</a-button>
                <a-button class="ml-2" size="small" @click="handleDelMutil">删除</a-button>
              </div>
            </template>
            <template #actions="{ record, index }">
              <div class="action flex">
                <a-button size="small" @click="handleEditBtn(record, index)">编辑</a-button>
              </div>
            </template>
          </HEditTable>
        </div>
      </div>
    </div>
    <div
      class="center aciton-shadow flex flex-col"
      :class="{
        preview: isPreview,
      }"
    >
      <div class="top mb-4 box-b-shadow">
        <div class="actions px-4 py-2 bg-white space-x-2">
          <a-button @click="openPlus" type="primary" size="small">新增</a-button>
          <a-button @click="handlePreview" size="small">预览</a-button>
        </div>
      </div>
      <div class="flex-1 px-4 center-body" v-if="isShow && formState.modelList.length">
        <HComplexPage
          preview
          class="h-[calc(100%-47px)]"
          :parentParam="formState.param"
          :parentQuery="formState.query"
          :pageType="formState.pageType"
          :buttons="formState.buttons"
          :data-source="formState.modelList"
          v-model:active="activePage"
          @del="handleDel"
        />
      </div>
      <HEmpty v-else class="!mt-[10vh]" />
    </div>
    <div
      v-if="isShow"
      class="right box-l-shadow"
      :class="{
        hide: isPreview,
      }"
    >
      <HTabs
        class="px-2"
        v-model:active="activeTab"
        :dataSource="tabSource"
        @change="changeRTabs"
      />

      <div class="p-4" v-if="curModelItem">
        <BasicForm @register="registerForm" @field-value-change="changeComplexItem" />
      </div>
      <HEmpty v-else class="!mt-[10vh]" />
    </div>
    <PlusTabPageModal @register="registerPlusModal" @success="handleAdd" />
    <ButtonConfigModal :classify="2" @register="registerBtnModal" @success="handleSuccessBtn" />
  </div>
</template>

<script lang="ts" setup name="ComplexDesign">
  import { ref, unref, watch, nextTick, computed } from 'vue';
  import FormTitle from '/@/components/HFormTitle';
  import HComplexPage from '/@/components/HComplexPage/index.vue';
  import { ComplexContainer, PageTypeEnum } from '/@/components/HComplexPage/typing';
  import ButtonConfigModal from '/@/views/config-center/model-design/components/ButtonConfigModal.vue';
  import PlusTabPageModal from './PlusTabPageModal.vue';
  import { HTabs } from '/@/components/HTabs';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { HEditTable } from '/@/components/HEditTable';
  import HEmpty from '/@/components/HEmpty/index.vue';

  import { useDesign } from '/@/hooks/web/useDesign';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { propTypes } from '/@/utils/propTypes';
  import { pageSchema, multiTabs, tiledTabs, tabSchemas, buttonsColumn } from './data';

  const props = defineProps({
    isShow: propTypes.bool,
    data: propTypes.object.def({ pageType: 'tab', modelList: [] }),
    update: propTypes.bool.def(false),
    client: propTypes.number.def(0),
  });
  const { createMessage } = useMessage();
  const activeTab = ref(1);

  const tabSource = ref(multiTabs);
  const formState = ref<ComplexContainer>({
    pageType: PageTypeEnum.TAB,
    modelList: [],
    buttons: [],
  });

  const showTab = computed(() => {
    console.log(
      '%cformState.value.pageType===>121： ',
      'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
      formState.value.pageType,
    );

    return formState.value.pageType === PageTypeEnum.TAB;
  });
  const buttonColumn = ref<any[]>([]);

  const { prefixCls } = useDesign('complex-design');
  const curModelItem = ref();

  const [registerAppForm, { resetFields: appReset, setFieldsValue: appSet, validate: appValid }] =
    useForm({
      layout: 'vertical',
      schemas: pageSchema,
      baseColProps: { span: 24 },
      showActionButtonGroup: false,
    });

  const [registerForm, { setProps, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    baseColProps: { span: 24 },
    showActionButtonGroup: false,
  });

  watch(
    () => props.isShow,
    async (v) => {
      if (!v) return;

      init();
    },
  );

  async function init() {
    const { pageType = PageTypeEnum.TAB, modelList, buttons } = props.data;
    if (props.update) {
      formState.value = {
        ...props.data,
        pageType,
        modelList: modelList || [],
        buttons: buttons || [],
      };
    }

    buttonColumn.value = await buttonsColumn();

    tabSource.value = pageType === PageTypeEnum.TAB ? multiTabs : tiledTabs;

    const tabFirst = formState.value.modelList[0];
    if (tabFirst) {
      curModelItem.value = tabFirst;
    }
    nextTick(async () => {
      if (tabFirst) {
        setProps({
          schemas: tabSchemas(pageType, props.client),
        });

        setFieldsValue(unref(curModelItem));
      }
      appReset();
      appSet(props.data);
    });
  }

  const isPreview = ref(false);
  function handlePreview() {
    isPreview.value = !isPreview.value;
  }

  const [registerPlusModal, { openModal: openPlusTabPageModal }] = useModal();
  const activePage = ref(0);
  watch(
    () => activePage.value,
    async () => {
      setComplexItem();
    },
  );

  function openPlus() {
    openPlusTabPageModal(true, {
      pageType: formState.value.pageType,
      modelList: formState.value.modelList,
      client: props.client,
    });
  }

  function setComplexItem() {
    curModelItem.value = formState.value.modelList[activePage.value];

    nextTick(() => {
      tabSource.value = formState.value.pageType === PageTypeEnum.TAB ? multiTabs : tiledTabs;
      setProps({
        schemas: tabSchemas(formState.value.pageType, props.client),
      });
      resetFields();
      setFieldsValue(unref(curModelItem));
    });
  }

  async function handleAdd(data) {
    await nextTick();

    formState.value.modelList.push(data);

    activePage.value = !curModelItem.value ? 0 : formState.value.modelList.length - 1;
    if (activePage.value === 0) {
      setComplexItem();
    }
  }

  function handleDel(idx) {
    formState.value.modelList.splice(idx, 1);
    if (!formState.value.modelList.length) {
      curModelItem.value = undefined;
    }
  }
  function changeComplexItem(key, value) {
    curModelItem.value[key] = value;
  }
  async function changeComplexContainer(key, value) {
    await nextTick();
    if (key === 'pageType') {
      tabSource.value = value === PageTypeEnum.TAB ? multiTabs : tiledTabs;
      if (curModelItem.value) {
        setProps({
          schemas: tabSchemas(value, props.client),
        });
      }
    }

    formState.value[key] = value;
  }

  function changeRTabs() {}

  const handleDelMutil = () => {
    const arr = formState.value.buttons || [];
    const data = arr.filter((el) => el.check);
    if (!data.length) {
      createMessage.warn('请先选择要删除的列', 0.8);
      return;
    }

    formState.value.buttons = arr.filter((el) => !el.check);
  };

  const [registerBtnModal, { openModal: tableButtonsModal }] = useModal();

  const handleAddBtn = () => {
    tableButtonsModal(true, {
      isUpdate: false,
    });
  };
  const handleEditBtn = (record, index) => {
    tableButtonsModal(true, {
      isUpdate: true,
      record,
      index,
    });
  };
  const handleSuccessBtn = ({ isUpdate, index, record }) => {
    if (isUpdate) {
      formState.value.buttons?.splice(index, 1, record);
      return;
    }
    formState.value.buttons?.push(record);
  };

  defineExpose({
    async getValues() {
      await appValid();
      return unref(formState);
    },
  });
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-complex-design';

  .@{prefix-cls} {
    position: relative;
    height: 100%;

    .left {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      z-index: 1;
      padding: 8px 16px;
      width: 280px;
      margin-right: 16px;
      transition: all 0.3s;

      &.hide {
        margin-left: -280px;
      }
    }

    .center {
      height: 100%;
      margin: 0 294px;
      background-color: @content-bg;
      transition: all 0.3s;

      &.preview {
        margin: 0;
      }

      .center-body {
        height: calc(100% - 80px);
        overflow: auto;
      }
    }

    .right {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      margin-right: 0;
      width: 280px;
      transition: all 0.3s;

      &.hide {
        margin-right: -280px;
      }
    }
  }
</style>
